#include "playlists.h"

PlayLists::PlayLists(QString *accessToken)
{
    if (accessToken != NULL)
    {
        this->accessToken = accessToken;
        searchTextBuffer = "";
        audioGetUrl = "https://api.vkontakte.ru/method/audio.get.xml?&access_token="+(*accessToken);
        audioSearchUrl = "https://api.vkontakte.ru/method/audio.search.xml?&sort=2&count=10&access_token="+(*accessToken)+"&q="+searchTextBuffer;
        manager = new QNetworkAccessManager();
        connect(manager,SIGNAL(finished(QNetworkReply*)),this,SLOT(finishRequest(QNetworkReply*)));

        QUrl url_audioGet(audioGetUrl);
        request_getPlayList =new QNetworkRequest(url_audioGet);
        manager->get(*request_getPlayList);

        struct_playlistCurrent = NULL;
        struct_playlistFull = new PlayLists::List();
        struct_playlistFull->album_id = "audio";
        struct_playlistFull->current_track = 0;
        struct_playlistFull->model_playlist = new QStandardItemModel();
        struct_playlistFull->model_playlist->setColumnCount(7);
        struct_playlistFull->owner_id = "none";
        struct_playlistFull->title = "audio";
        struct_playlistSearch = new PlayLists::List();
        struct_playlistSearch->album_id = "search";
        struct_playlistSearch->current_track = 0;
        struct_playlistSearch->model_playlist = new QStandardItemModel();
        struct_playlistSearch->model_playlist->setColumnCount(7);
        struct_playlistSearch->owner_id = "none";
        struct_playlistSearch->title = "search";
    }
}

void PlayLists::AddPlayList(QString playlist_name)
{
    PlayLists::List *new_playlist = new PlayLists::List();
    new_playlist->title = playlist_name;
    new_playlist->model_playlist = new QStandardItemModel(this);
    new_playlist->model_playlist->setColumnCount(7);
    new_playlist->current_track=0;
    map_playlist->insert(playlist_name,new_playlist);
}

bool PlayLists::removePlayList(QString playlist_name)
{
    //Текущий плейлист, основной плейлист и плейлист поиска нельзя удалить
    if(struct_playlistCurrent->title != playlist_name &&
       struct_playlistCurrent != struct_playlistFull &&
       struct_playlistCurrent != struct_playlistSearch)
    {
        map_playlist->remove(playlist_name);
        return true;
    }
    else
    {
        return false;
    }
}

bool PlayLists::setCurrentPlayList(QString playlist_name)
{
    if(map_playlist->contains(playlist_name))
    {
        struct_playlistCurrent = map_playlist->value(playlist_name);
        return true;
    }
    else
    {
        if (playlist_name == "audio")
        {
            struct_playlistCurrent = struct_playlistFull;
            return true;
        }
        if (playlist_name == "search")
        {
            struct_playlistCurrent = struct_playlistSearch;
            return true;
        }
    }
    return false;
}

PlayLists::List* PlayLists::getCurrentPlayList()
{
    return struct_playlistCurrent;
}

int PlayLists::getCurrentTrack()
{
    return struct_playlistCurrent->current_track;
}

bool PlayLists::setCurrentTrack(int currentTrack)
{
    if (currentTrack < struct_playlistCurrent->model_playlist->rowCount())
    {
        struct_playlistCurrent->current_track = currentTrack;
        return true;
    }
    return false;
}


void PlayLists::finishRequest(QNetworkReply *reply)
{
    //Пришел ответ на запрос получения основного списка
    if (reply->request().url().toString() == audioGetUrl)
    {
        QByteArray byte;
        byte = reply->readAll();

        reply->deleteLater();
        delete request_getPlayList;
        load_list("playlists/audio.xml", struct_playlistFull->model_playlist, byte);
    }
    //Пришел ответ на запрос поиска
    if (reply->request().url().toString() == audioSearchUrl+searchTextBuffer)
    {
        QByteArray byte;
        byte = reply->readAll();

        reply->deleteLater();
        delete request_getPlayList;
        load_list("playlists/search.xml", struct_playlistSearch->model_playlist, byte);
    }
}

bool PlayLists::searchTrack(QString track_name)
{
    searchTextBuffer = track_name; 
    QUrl url_audioGet(audioSearchUrl+searchTextBuffer);
    request_getPlayList =new QNetworkRequest(url_audioGet);
    manager->get(*request_getPlayList);

    return true;
}

void PlayLists::load_list(QString filename, QStandardItemModel *model, QByteArray source)
{
    QFile file (filename);
    if (file.open(QIODevice::ReadOnly))
    {
        if (xml_document->setContent(source))
        {
            model->clear();
            //Устанавливаем исходный текст с XML
            model->setRowCount(0);
            model->setColumnCount(3);

            QDomElement xmlElement = xml_document->documentElement(); //Выбираем первый элемент в xml документе, им является: <response list="true">
            if (xmlElement.attribute("list","") == "true") //Проверяем его атрибут: list
            {
                traverseNode(xmlElement,model); //Вызываем рекурсивную функцию обработки xml документа. Xml документ представляет собой иерархическую структуру
            }
        }
    }
}

void PlayLists::traverseNode(const QDomNode &node, QStandardItemModel *model)
{
    QDomNode xmlNode = node.firstChild(); //Выбираем первый дочерний элемент, в 1 вызове им является элемент <audio>, при втором вызове им будет <aid>, но его пропускаем и переходим на следующую итерацию цикла
    while(!xmlNode.isNull())
    {
        if (xmlNode.isElement())
        {
            QDomElement xmlElement = xmlNode.toElement();
            if (!xmlElement.isNull())
            {
                if(xmlElement.tagName() == "audio") //Если текущий элементом (блоком) является audio, следовательно добавляем строчку в модель
                {
                    model->insertRow(model->rowCount()); //Добавляем строчку в конец таблицы в модели
                }
                if(xmlElement.tagName() == "aid")
                {
                    QModelIndex index = model->index(model->rowCount()-1,0,QModelIndex());
                    model->setData(index,xmlElement.text());
                }
                if(xmlElement.tagName() == "owner_id")
                {
                    QModelIndex index = model->index(model->rowCount()-1,1,QModelIndex());
                    model->setData(index,xmlElement.text());
                }
                if(xmlElement.tagName() == "artist")
                {
                    QModelIndex index = model->index(model->rowCount()-1,2,QModelIndex());
                    model->setData(index,xmlElement.text());
                }
                if(xmlElement.tagName() == "title")
                {
                    QModelIndex index = model->index(model->rowCount()-1,3,QModelIndex());
                    model->setData(index,xmlElement.text());
                }
                if(xmlElement.tagName() == "duration")
                {
                    QModelIndex index = model->index(model->rowCount()-1,4,QModelIndex());
                    model->setData(index,xmlElement.text());
                }
                if(xmlElement.tagName() == "url")
                {
                    QModelIndex index = model->index(model->rowCount()-1,5,QModelIndex());
                    model->setData(index,xmlElement.text());
                }
            }
        }
        traverseNode(xmlNode,model);
        xmlNode = xmlNode.nextSibling();
    }
}

bool PlayLists::saveToFile(QString playlist_name)
{
    /*EXAMPLE
    <audio>
    <aid>132087077</aid>
    <owner_id>10719484</owner_id>
    <artist>░The Prodigy░</artist>
    <title>Breath</title>
    <duration>238</duration>
    <url>http://cs4711.vkontakte.ru/u52186745/audio/47a7ba0caa1a.mp3</url>
    <lyrics_id>6796786</lyrics_id>
    </audio>
      */

    QStandardItemModel *model_playlist = map_playlist->value(playlist_name)->model_playlist;
    int currentRow = 0;

    QDomDocument doc(playlist_name);

    while (currentRow < model_playlist->rowCount())
    {
        QDomElement domElement_audio = doc.createElement("audio");
        doc.appendChild(domElement_audio);

        QDomElement domElement_aid = doc.createElement("aid");
        QDomText domText_aid = doc.createTextNode(model_playlist->item(currentRow,0)->text());
        domElement_aid.appendChild(domText_aid);
        domElement_audio.appendChild(domElement_aid);

        QDomElement domElement_owner_id = doc.createElement("owner_id");
        QDomText domText_owner_id = doc.createTextNode(model_playlist->item(currentRow,1)->text());
        domElement_owner_id.appendChild(domText_owner_id);
        domElement_audio.appendChild(domElement_owner_id);

        QDomElement domElement_artist = doc.createElement("artist");
        QDomText domText_artist = doc.createTextNode(model_playlist->item(currentRow,2)->text());
        domElement_owner_id.appendChild(domText_artist);
        domElement_audio.appendChild(domElement_artist);

        QDomElement domElement_title = doc.createElement("title");
        QDomText domText_title = doc.createTextNode(model_playlist->item(currentRow,3)->text());
        domElement_owner_id.appendChild(domText_title);
        domElement_audio.appendChild(domElement_title);

        QDomElement domElement_duration = doc.createElement("duration");
        QDomText domText_duration = doc.createTextNode(model_playlist->item(currentRow,4)->text());
        domElement_owner_id.appendChild(domText_duration);
        domElement_audio.appendChild(domElement_duration);

        QDomElement domElement_url = doc.createElement("url");
        QDomText domText_url = doc.createTextNode(model_playlist->item(currentRow,5)->text());
        domElement_owner_id.appendChild(domText_url);
        domElement_audio.appendChild(domElement_url);

        QDomElement domElement_lyrics_id = doc.createElement("lyrics_id");
        QDomText domText_lyrics_id = doc.createTextNode(model_playlist->item(currentRow,6)->text());
        domElement_owner_id.appendChild(domText_lyrics_id);
        domElement_audio.appendChild(domElement_lyrics_id);
        currentRow++;
    }


    QFile file("playlists/"+playlist_name+".xml");
    file.open(QIODevice::WriteOnly);
    QTextStream stream(&file);
    doc.save(stream,1);
}


bool PlayLists::addInPlayList(int track, QString from_playlist_name, QString to_playlist_name)
{

    QStandardItemModel *from = map_playlist->value(from_playlist_name)->model_playlist;
    QStandardItemModel *to = map_playlist->value(to_playlist_name)->model_playlist;

    if (track < from->rowCount())
    {
        to.insertRow(0);
        to.setItem(0,0,QStandardItem(from.item(track,0)));
        to.setItem(0,1,QStandardItem(from.item(track,1)));
        to.setItem(0,2,QStandardItem(from.item(track,2)));
        to.setItem(0,3,QStandardItem(from.item(track,3)));
        to.setItem(0,4,QStandardItem(from.item(track,4)));
        to.setItem(0,5,QStandardItem(from.item(track,5)));
        to.setItem(0,6,QStandardItem(from.item(track,6)));
        return true;
    }
    return false;
}


